import Radio from "backbone.radio";
import { getOpt } from "../../tools";

const FacadeModelApiMixin = {
    channelName: 'facade',
    setModelUrl(label, url){
        this.models[label].url = url;
    },
    setCollectionUrl(label, url){
        this.collections[label].url = url;
    },
    loadModel(label){
        let model = this.models[label];
        let request = model.fetch();
        return request.then(function(){return model;});
    },
    loadCollection(label, params){
        /*
         * Load a collection and returns the collection itself
        */
        let options = {}
        if (params){
            options['data'] = params;
            options['processData'] = true;
        }
        if (!label in this.collections){
            console.error("Unknown collection : %s", label);
        }
        let collection = this.collections[label];
        let request = collection.fetch(options);
        return request.then(function(){return collection});
    },
    getCollectionRequest(label){
        return this.collections[label];
    },
    getModelRequest(label){
        return this.models[label];
    },
    saveModel(modelName){
        console.log("FacadeModelApiMixin.saveModel", modelName);
        let model = this.models[modelName];
        if (model.isLocalModel) {
            console.log(`Skipping ${modelName} save (local model)`);
            // No-op -> always a success !
            return $.Deferred().resolve();
        } else {
            console.log(`Saving ${modelName}`)
            
            let pendingChanges = model.changedAttributes();
            let result;
            if (pendingChanges){
                console.log(" + Running save")
                result = model.save(
                    model.changedAttributes,
                    {wait: true, sync: true, patch: true}
                );
            } else {
                console.log(" + No pending changes")
                result = Promise.resolve({})
            }
            return result;
        }
    },
    isDataValid(){
        var channel = Radio.channel('facade');
        channel.trigger('bind:validation');
        var result = {};
        _.each(this.models, function(model){
            const validate_func = model['validate'];
            if (validate_func){
                var res = model.validate();
                if (res){
                    _.extend(result, res);
                }
            }
        });
        _.each(
            this.collections,
            function(collection, label){
                const validate_func = collection['validate'];
                if (validate_func){
                    var res = collection.validate();
                    if (res){
                        _.extend(result, res);
                    }
                }
            }
        );
        channel.trigger('unbind:validation');
        console.log("End of isDataValid");
        console.log(result);
        return result;
    },
    saveAll(){
        // Hack pour checker si les objets gérés par la Facade sont bien éditables
        // Dans le cas contraire, le saveAll doit renvoyer une promise quand même
        // Dans le cas des docs fournisseurs par exemple, on peut rajouter des fichiers après validation
        // Ref : https://framagit.org/endi/endi/-/issues/2712
        let editable = getOpt(this, 'edit', true);
        if (!editable){
            return new Promise((resolve, reject) => {return {}});
        }
        let this_ = this;
        let keys = _.keys(this.models);
        let deferreds = []
        keys.forEach(function(modelName){
            deferreds.push(this_.saveModel(modelName));
        })
        return $.when(...deferreds);
    },
};
export default FacadeModelApiMixin;
